%{
    This file is part of StemCellQC, a video bioinformatics software
    toolkit for analysis of phase contrast microscopy videos.
    Copyright 2013-2015 Vincent On. [vincenton001-at-gmail.com]

    StemCellQC is free software: you can redistribute it and/or 
    modify it under the terms of the GNU General Public License as 
    published by the Free Software Foundation, either version 3 of the 
    License, or (at your option) any later version.

    StemCellQC is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with StemCellQC.  If not, see <http://www.gnu.org/licenses/>.
%}

function fun_segment_multi( index, segmentation_gain, min_area)
global mov


filtSize = 1;

% Normalize the image
temp = double(mov(index).data) - min(min( double(mov(index).data) ));
temp = temp ./ max(max( temp ));

temp = imadjust( temp );
% Blur it a little bit
temp = imfilter( temp, ...
    fspecial( 'gaussian', (1+2*2*filtSize) ), ...
    'symmetric' );


% Entropy filter: The cell is a uniform texture
temp = entropyfilt( temp, true((1+2*filtSize)) );
temp = temp - min(min( temp ));
temp = temp ./ max(max( temp ));


% I_min = min(min( double(mov(index).data) ));
% I_max = max(max( double(mov(index).data) ));
% temp = ((double(mov(index).data) - I_min)./(I_max - I_min))*255;

% Opening: we want small 'balls' touching the cell to stop touching
%{
        TODO: The following section could be improved. It doesn't always
        prevent non-cell objects from being counted as a part of the cell.
%}
temp = imopen( temp, ...
    strel('disk',round((1+2*3*filtSize)*segmentation_gain)) ); %try larger disc sizes if segmentation is picking up too much

% Now threshold
[ thres,EM] = graythresh( temp );
temp = im2bw( temp, thres );

temp = bwareaopen( temp, min_area );

% Fill it
temp = imfill( temp , 'holes');

% SAVE IT HERE
mov(index).EM = EM;
mov(index).segmented = temp;
